# -*- coding: utf-8 -*-
import gc
import json
import logging
from common import orm
from common.export.model import EXPORT_STATUS, ExportDb
from common.utils.decorator import sql_wrapper
from common.utils.export import redirect_to_file, gen_filename
from common.order import admin_db as order_db

_LOGGER = logging.getLogger(__name__)

@sql_wrapper
def export_data_start(user_id, condition, desc=''):
    item = ExportDb.query.filter(ExportDb.user_id == user_id).filter(ExportDb.status.in_([EXPORT_STATUS.START, EXPORT_STATUS.PROCESSING])).first()
    if item is not None:
        return item.id
    export = ExportDb()
    export.user_id = user_id
    export.condition = condition
    export.status = EXPORT_STATUS.START
    export.desc = desc
    export.url = '/export_data/' + gen_filename('pay')
    export.save()
    orm.session.commit()
    return export.id


@sql_wrapper
def process_export(export_id):
    export = ExportDb.query.filter(ExportDb.id == export_id).filter(ExportDb.status == EXPORT_STATUS.START).first()
    if export is None:
        return
    export.status = EXPORT_STATUS.PROCESSING
    export.save()
    orm.session.commit()
    cn_header = ['id', u'商户订单号', u'用户ID', u'通道订单号', u'创建时间',
                 u'商户ID', u'通道ID', u'通道名称', u'充值金额',
                 u'支付时间', u'支付状态']
    try:
        resp_items = order_db.export_order(json.loads(export.condition))
        redirect_to_file(resp_items, cn_header, export.url.replace('/export_data/', ''))
        export.status = EXPORT_STATUS.COMPLETE
        del resp_items
        gc.collect()
    except Exception as e:
        error_msg = 'process_export[%s] exception : %s' % (export_id, e)
        print error_msg
        _LOGGER.exception(error_msg)
        export.status = EXPORT_STATUS.FAIL
    export.save()
    orm.session.commit()


@sql_wrapper
def process_export_reconciliation(export_id):
    export = ExportDb.query.filter(ExportDb.id == export_id).filter(ExportDb.status == EXPORT_STATUS.START).first()
    if export is None:
        return
    export.status = EXPORT_STATUS.PROCESSING
    export.save()
    orm.session.commit()
    cn_header = [u'订单号', u'公司订单号', u'通道订单号', u'创建时间', u'公司',
                 u'金额', u'到账时间', u'是否隔天到帐', u'是否补单']
    try:
        resp_items = order_db.export_reconciliation_order(json.loads(export.condition))
        redirect_to_file(resp_items, cn_header, export.url.replace('/export_data/', ''))
        export.status = EXPORT_STATUS.COMPLETE
        del resp_items
        gc.collect()
    except Exception as e:
        error_msg = 'process_export_reconciliation[%s] exception : %s' % (export_id, e)
        print error_msg
        _LOGGER.exception(error_msg)
        export.status = EXPORT_STATUS.FAIL
    export.save()
    orm.session.commit()


@sql_wrapper
def get_export_status_by_user_id(user_id):
    return ExportDb.query.filter(ExportDb.user_id == user_id).order_by(ExportDb.id.desc()).first()
